package sh.ds.el.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import sh.ds.el.dao.base.ElDao;
import sh.ds.el.entity.UserVO;
import sh.ds.el.enums.CommonEnums;

@Repository
public class UserDao extends ElDao {

	/**
	 * 获得满足条件的用户数量
	 *
	 * @param queryVo
	 * @return
	 */
	public Long queryUserCount(UserVO queryVo) {
		StringBuffer hql = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		
		hql.append(" select count(t.userId) ");
		hql.append(" from 	UserVO t ");
		hql.append(" where 	1 = 1 ");
		hql.append(" and	t.validity = ? ");
		params.add(CommonEnums.VALIDITY.VALID);
		if (queryVo != null) {
			if (StringUtils.hasText(queryVo.getUserCode())) {
				hql.append(" and t.userCode = ? ");
				params.add(queryVo.getUserCode());
			}
			if (StringUtils.hasText(queryVo.getPassword())) {
				hql.append(" and t.password = ? ");
				params.add(queryVo.getPassword());
			}
		}
		
		Long result = getEntityManager().find(Long.class, hql.toString(), params).get(0);
		return result;
	}
	
	public UserVO queryUniqueUser(UserVO queryVo) {
		StringBuffer hql = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		
		hql.append(" select t ");
		hql.append("   from UserVO t ");
		hql.append("  where 1 = 1 ");
		if (queryVo != null) {
			if (StringUtils.hasText(queryVo.getUserCode())) {
				hql.append(" and t.userCode = ? ");
				params.add(queryVo.getUserCode());
			}
			if (StringUtils.hasText(queryVo.getPassword())) {
				hql.append(" and t.password = ? ");
				params.add(queryVo.getPassword());
			}
		}
		
		List<UserVO> result = getEntityManager().find(UserVO.class, hql.toString(), params);
									
		if (!CollectionUtils.isEmpty(result) && result.size() == 1) {
			return result.get(0);
		}
		return null;
	}
	
}
